package com.cn.jdia.dc.controller;

import java.io.IOException;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.jdia.dc.model.Accesstoken;
import com.cn.jdia.dc.service.IAccessService;

@Controller
public class CheckLoginController {

	@Resource
	private IAccessService accessService;

	@RequestMapping(value = "/checklogin")
	@ResponseBody
	public String checkLogin(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("username") String name, @RequestParam("password") String pwd) throws IOException {

		// System.out.println(pwd);

		// accessService = (IAccessService)
		// SpringContextUtils.getContext().getBean("accessService");
		Accesstoken access = accessService.checklogin(name, pwd);

		int id = 0;
		String pname = null;
		String dept = null;
		String idCard = null;

		if (access != null) {
			id = access.getPersonid();
			pname = access.getPersonname();
			dept = access.getPersondept();

			request.getSession().setAttribute("islogin", "true");

			String encode = URLEncoder.encode(pname, "UTF-8");
			Cookie username_cookie = new Cookie("pname", encode);
			username_cookie.setMaxAge(60*60*24*5);
			response.addCookie(username_cookie);

			return "0";
		} else {
			System.out.println("access is null");
			return "1";
		}
	}

	@RequestMapping(value = "/logout")
	public String loginOut(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("loginout");
		request.getSession().removeAttribute("islogin");

		Cookie deletePnameCookie = new Cookie("pname", null);
		deletePnameCookie.setMaxAge(0);
		deletePnameCookie.setPath("/");
		response.addCookie(deletePnameCookie);

		return "index";
	}
}
